package com.easyfun.healthmagicbox.comm;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import android.content.Context;
import android.util.Log;

import com.easyfun.healthmagicbox.comm.json.ServerHeartBeatJsonWrapper;
import com.easyfun.healthmagicbox.comm.json.ServerHeartBeatListJsonWrapper;
import com.easyfun.healthmagicbox.ormlite.ServerResponseCode;
import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.pojo.HeartBeatMessage;
import com.easyfun.healthmagicbox.sync.CommCallback;

public class ServerHeartbeatTask extends BaseCommTask{
	private static final String TAG = ServerHeartbeatTask.class.getSimpleName();
	List<HeartBeatMessage> mhblist;
	public ServerHeartbeatTask(Context mcontext, CommCallback ccb, List<HeartBeatMessage> hblist) {
		super(mcontext, ccb);
		this.mhblist = hblist;
	}

	@Override
	public void run() {
		Map<String, String> parmas = new HashMap<String, String>();
		ServerHeartBeatListJsonWrapper<ServerHeartBeatListJsonWrapper> hblistwrapper = 
				new ServerHeartBeatListJsonWrapper<ServerHeartBeatListJsonWrapper>(mhblist);
		try {
			parmas.put("jsonstring", hblistwrapper.serialize());
		} catch (JSONException e1) {
			//log.e(TAG,e1.toString());
			e1.printStackTrace();
		}
		
		String result;
		try {
			result = super.uploadByHTTP(parmas,
					ConstantData.ServerHeartBeatURI);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			Log.e(TAG, e.toString());
			ccb.setCommResult(this,
					"", ServerResponseCode.FAILED);
			return;
		} catch (IOException e) {
			Log.e(TAG, e.toString());
			e.printStackTrace();
			ccb.setCommResult(this,
					"", ServerResponseCode.FAILED);
			return;
		}
		
		if (ServerResponseCode.parseOf(result)==ServerResponseCode.FAILED)
		{

			ccb.setCommResult(this,
					"", ServerResponseCode.FAILED);
			return;
		}else if (ServerResponseCode.parseOf(result)==ServerResponseCode.NOMORE)
		{

			ccb.setCommResult(this,
					"", ServerResponseCode.NOMORE);
			return;
		}else if (ServerResponseCode.parseOf(result)==ServerResponseCode.SUCCESS)
		{

			ccb.setCommResult(this,
					"", ServerResponseCode.SUCCESS);
			return;
		}else
		{
			//server has some changes, pass the result to sender
			ccb.setCommResult(this,
					result, ServerResponseCode.SUCCESS);
		}
		
	}

}
